//
// Created by benxb on 2021/11/16.
//

#ifndef BENXDB_DATA_CHUNK_DESC_H
#define BENXDB_DATA_CHUNK_DESC_H

#include <string>
#include <type/value.h>
#include <fstream>
#include "type/type.h"
#include "common/config.h"

namespace benxdb {

class ChunkDesc {
public:
    int64_t chunk_offset;
    int32_t chunk_size;
    TypeId type;
    CompressStrategy compress_mode;
    Value min_val;
    Value max_val;
};

/**
 * DataChunkDescIO describe the info of data_ chunks
 * For example:
 * raw_data.data_ file has a raw_data.desc store its id/min_val/max_val/offset... of chunks
 * the format in raw_data.desc such like:
 * ----------------------------------------------------------------------------------------------------------
 * | ChunkOffset(64) | ChunkSize(32) | DataType(16) | CompressMode(16) | Min(64) | Max(64) |
 * ---------------------------------------------------------------------------------------------------------
 * We can easily get the offset and size of page_i from i*32 position,
 * and then we can use these to get data_ page from data_ file
 */
class DataChunkDescIO {
public:
    explicit DataChunkDescIO(const std::string& table_name);

    ~DataChunkDescIO();

    uint64_t AppendDesc(ChunkDesc desc);

    bool GetDescByChunkId(uint64_t chunk_id, ChunkDesc& desc);

    int64_t GetChunkCount();

    ChunkDesc GetDescByRecordId(uint64_t record_id, int64_t column_no);

    ChunkDesc GetDescByRecordId(uint64_t record_id);

    std::string GetDescFile() {
        return desc_file_;
    }

private:
    static const int OFFSET_CHUNK_OFFSET = 0;
    static const int OFFSET_CHUNK_SIZE = 8;
    static const int OFFSET_DATA_TYPE = 12;
    static const int OFFSET_COMPRESS_MODE = 14;
    static const int OFFSET_MIN_VALUE = 16;
    static const int OFFSET_MAX_VALUE = 24;
    static const int SIZE_CHUNK_DESC = 68;
    static const int OFFSET_FIRST_DESC = 4;

    std::string table_name_;
    std::string desc_file_;
    std::fstream desc_io_;
    int64_t file_size_;
};

}

#endif //BENXDB_DATA_CHUNK_DESC_H
